//
//  YYSpreadSheetViewCell.swift
//  C018_test_spreadSheet
//
//  Created by yao_yu on 15/6/24.
//  Copyright © 2015年 yao_yu. All rights reserved.
//

import UIKit


class YYSpreadSheeetViewCell: UITableViewCell {
    
    private var cellLabels = [UILabel]()
    
    var margin:CGFloat = 0 {
        didSet {
            setNeedsLayout()
        }
    }
    
    var cellSpace:CGFloat = 0 {
        didSet {
            setNeedsLayout()
        }
    }
    
    var rowData: [String:String]!{
        didSet {
            for (i,(key, _)) in colWidths.enumerate() {
                if let value = rowData[key] {
                    cellLabels[i].text = value
                }
            }
            setNeedsLayout()
        }
    }
    
    var colWidths: [(String, CGFloat)]! {
        didSet {
            let (oldCount, newCount) = (oldValue.count, colWidths.count)
            
            if newCount > oldCount {
                for i in oldCount ..< newCount {
                    cellLabels[i] = UILabel()
                    contentView.addSubview(cellLabels[i])
                }
            } else if newCount < oldCount{
                for i in newCount ..< oldCount {
                    cellLabels[i].removeFromSuperview()
                }
                cellLabels[newCount ..< oldCount] = []
            }
            setNeedsLayout()
        }
    }
    
    private var widthFactors: [CGFloat] {
        let total:CGFloat = totalColWidth
        return colWidths.map { (item:(String, CGFloat)) -> CGFloat in
            item.1 / total
        }
    }
    
    private var totalColWidth:CGFloat {
        var total:CGFloat = 0
        for (_, width) in colWidths {
            total += width
        }
        return total
    }
    
    override func layoutSubviews() {
        let contentWidth = contentView.bounds.width - margin * 2
        
    }
    
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
    }
    
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}